﻿using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Text;
using Ping.Core;
using log4net;

namespace Ping.Server
{
	/// <summary>
	/// A little service that is able to log the current status of the server.
	/// </summary>
	public sealed class Status
	{
		private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		private readonly Server _server;


		public Status(Server server)
		{
			if (server == null)
				throw new ArgumentNullException();

			_server = server;
		}

		public void Write()
		{
			var status = new StatusResult(_server);

			var builder = new StringBuilder();
			builder.AppendFormat("Server Status:\n");
			builder.AppendFormat("Uptime: {0}\n", status.Uptime.Format());
			builder.AppendFormat("Num. Connections: {0}\n", _server.NumConnections);
			builder.AppendFormat("Num. Blacklisted IPs: {0}\n", _server.NumBlacklistedIPs);

			builder.Append("Memory:\n");
			builder.AppendFormat("Private Memory: {0}\n", Format(status.PrivateMemory));
			builder.AppendFormat("Peak Virtual Memory: {0}\n", Format(status.PeakVirtualMemory));
			builder.AppendFormat("Paged Process Memory: {0}\n", Format(status.PagedProcessMemory));
			builder.AppendFormat("Peak Paged Memory: {0}\n", Format(status.PeakPagedMemory));
			builder.AppendFormat("Paged System Memory: {0}\n", Format(status.PagedSystemMemory));
			builder.AppendFormat("Nonpaged System Memory: {0}\n", Format(status.NonpagedSystemMemory));

			builder.Append("Process:\n");
			builder.AppendFormat("Num. Threads: {0}\n", status.NumThreads);

			Log.Info(builder.ToString());
		}

		private static string Format(long size)
		{
			return Extensions.FormatSize(size);
		}
	}
}